<template>
  <div class="check-wrap">
    <div class="check-header">
      <span>{{ scopeItem?.label }}</span>
      <el-checkbox
        v-model="allCheckStatus"
        :indeterminate="isIndeterminate"
        @change="(value: boolean) => handleCheckAllChangeScope(value, props.scopeItem)"
        :disabled="props.readonly"
        >全选</el-checkbox
      >
    </div>
    <el-collapse class="role-tree" v-model="roleTreeCollapse">
      <el-collapse-item :name="menu.id" v-for="menu in props.menuList" :key="menu.id">
        <template #title>
          <el-checkbox
            @click.stop
            v-model="menu.checkStatus"
            :indeterminate="menu.isIndeterminate"
            :disabled="props.readonly"
            @change="(value: boolean) => handleCheckAllChange(value, 
            
            
            menu)"
          ></el-checkbox>
          <span>{{ menu.label }}</span>
        </template>
        <div class="role-tree-node__children">
          <el-checkbox-group
            v-model="menu.checkedRoles"
            :disabled="props.readonly"
            @change="(value: string[]) => handleCheckedCitiesChange(value, menu)"
          >
            <template v-if="menu.children?.length && menu.children[0]?.children?.length">
              <template v-for="menuMiddle in menu.children" :key="menuMiddle.id">
                <div class="role-tree-node__middle-title">{{ menuMiddle.label }}</div>
                <div class="role-tree-node__children-content">
                  <div
                    class="role-tree-node__content"
                    v-for="permission in menuMiddle.children"
                    :key="permission.id"
                  >
                    <el-checkbox :key="permission.id" :label="permission.id">
                      <GTooltip :content="permission.label">
                        <span class="permission-text g-ell">{{ permission.label }}</span>
                      </GTooltip>
                    </el-checkbox>
                  </div>
                </div>
              </template>
            </template>
            <template v-else>
              <div class="role-tree-node__children-content">
                <div
                  class="role-tree-node__content"
                  v-for="permission in menu.children"
                  :key="permission.id"
                >
                  <el-checkbox :key="permission.id" :label="permission.id">
                    <GTooltip :content="permission.label">
                      <span class="permission-text g-ell">{{ permission.label }}</span>
                    </GTooltip>
                  </el-checkbox>
                </div>
              </div>
            </template>
          </el-checkbox-group>
        </div>
      </el-collapse-item>
    </el-collapse>
  </div>
</template>
<script lang="ts" setup name="RoleTree">
import { withDefaults, defineProps, defineEmits, defineExpose, ref } from 'vue';
import { GTooltip } from '@/components/GTooltip/index';
import type { MenuListItem, ScopeItem } from '../types';
interface RoleTreePropsType {
  menuList: MenuListItem[];
  readonly: boolean;
  scopeItem: ScopeItem;
}

const props = withDefaults(defineProps<RoleTreePropsType>(), {
  readonly: false
});
const emit = defineEmits(['onSetRootMenu']);

const roleTreeCollapse = ref<number[]>([]);

const allCheckStatus = ref(false);
const isIndeterminate = ref(false);
function collapseOpenAll() {
  roleTreeCollapse.value = props.menuList.map(item => item.id);
}

// 一级菜单全选操作
const handleCheckAllChange = (val: boolean, menu: MenuListItem, setRoot = true) => {
  console.log('handleCheckAllChange', val, menu, setRoot);
  if (props.readonly) return;
  menu.checkStatus = val;
  let children = getChildrenPermission(menu);
  menu.checkedRoles = val ? children : [];
  menu.isIndeterminate = false;
  // 更新根节点状态
  setRoot && handleSetRootMenu(menu);
};
// 按钮权限勾选操作
const handleCheckedCitiesChange = (value: string[], menu: MenuListItem) => {
  if (props.readonly) return;
  const checkedCount = value.length;
  let children = getChildrenPermission(menu);
  menu.checkStatus = checkedCount === children?.length;
  menu.isIndeterminate = checkedCount > 0 && checkedCount < children?.length;
  // 更新根节点状态
  handleSetRootMenu(menu);
};
// 获取按钮权限
function getChildrenPermission(menu: MenuListItem) {
  let children: number[] = [];
  if (menu.children?.length && menu.children[0]?.children?.length) {
    let itemChildren: number[] = [];
    for (let i in menu.children) {
      const item = menu.children[i];
      if (item.children?.length) {
        itemChildren = [...itemChildren, ...item.children?.map((item: any) => item.id)];
      }
    }
    children = itemChildren;
  } else {
    children = menu.children?.map((item: any) => item.id) || [];
  }
  return children;
}

function handleSetRootMenu(menu: any) {
  emit('onSetRootMenu', menu);
  updateStatus();
}

// 获取所有以选中/半选中的菜单id
function getCheckedOrIndeterminateMenuId(menuList: MenuListItem[]) {
  console.log('getCheckedOrIndeterminateMenuId', menuList, props.menuList);
  let ids: number[] = [];
  for (let i = 0; i < menuList.length; i++) {
    const itemI = menuList[i];
    console.log('getCheckedOrIndeterminateMenuId itemI', itemI, itemI.checkedRoles?.length);
    if (itemI.checkStatus || itemI.isIndeterminate) {
      ids.push(itemI.id);
    }
    if (itemI.children?.length) {
      for (let j = 0; j < itemI.children.length; j++) {
        const itemJ = itemI.children[j];
        console.log('getCheckedOrIndeterminateMenuId itemJ', itemJ);
        if (itemJ.children?.length) {
          for (let k = 0; k < itemJ.children.length; k++) {
            const itemK = itemJ.children[k];
            console.log('getCheckedOrIndeterminateMenuId itemK', itemK.label);
            // 已勾选三级的按钮权限，自动加入二级的id
            if (itemI.checkedRoles.includes(itemK.id)) {
              ids.push(itemJ.id);
              break;
            }
          }
        }
      }
    }
    if (itemI.checkedRoles?.length) {
      ids = [...ids, ...itemI.checkedRoles];
    }
  }
  return ids;
}

function handleCheckAllChangeScope(val: boolean, scope: ScopeItem) {
  console.log('handleCheckAllChangeScope', val, scope);
  isIndeterminate.value = false;
  if (val) {
    for (let i in props.menuList) {
      const item = props.menuList[i];
      handleCheckAllChange(true, item, false);
    }
  } else {
    for (let i in props.menuList) {
      const item = props.menuList[i];
      handleCheckAllChange(false, item, false);
    }
  }
}
const updateStatus = () => {
  const checkedRoles = [...new Set(props.scopeItem.checkedRoles)];
  const indeterminateRoles = [...new Set(props.scopeItem.indeterminateRoles)];
  if (indeterminateRoles.length) {
    const allCheckStatus = ref(false);
    const isIndeterminate = ref(false);
    allCheckStatus.value = false;
    isIndeterminate.value = true;
  } else if (checkedRoles.length && checkedRoles.length === props.scopeItem.allCheckRoles.length) {
    allCheckStatus.value = true;
    isIndeterminate.value = false;
  } else if (checkedRoles.length && checkedRoles.length < props.scopeItem.allCheckRoles.length) {
    allCheckStatus.value = false;
    isIndeterminate.value = true;
  } else {
    allCheckStatus.value = false;
    isIndeterminate.value = false;
  }
};

defineExpose({
  collapseOpenAll,
  handleCheckAllChange,
  getCheckedOrIndeterminateMenuId
});
</script>
<style lang="scss" scoped>
:deep(.el-collapse.role-tree) {
  border-top: 0;
  border-bottom: 0;
  .el-collapse-item {
    min-height: 40px;
    .el-collapse-item__header {
      padding-left: 16px;
      height: 40px;
      background: #f8fbfc;
      font-size: 14px;
      font-weight: 400;
      color: #0a1f33;
      border-bottom-color: #e4e7ed;
      &:is-active {
        border-bottom-color: #e4e7ed;
      }
      > label.el-checkbox {
        margin-right: 5px;
      }
      > span {
        line-height: 40px;
        height: 40px;
      }
      > .el-collapse-item__arrow {
        margin-right: 16px;
        transform: rotate(-90deg);
        color: #435970;
        &.is-active {
          transform: rotate(90deg);
        }
      }
    }
    .el-collapse-item__content {
      padding-bottom: 0;
      .role-tree-node__children {
        // padding: 8px 0;
        background: #fff;
        .role-tree-node__middle-title {
          padding-top: 9px;
          padding-left: 16px;
          color: #7a8a99;
          font-size: 14px;
          line-height: 22px;
        }
        .role-tree-node__children-content {
          display: flex;
          justify-content: flex-start;
          flex-wrap: wrap;
          .role-tree-node__content {
            padding-left: 16px;
            display: flex;
            align-items: center;
            height: 40px;
            width: 154px;
            height: 32px;
            > label.el-checkbox {
              .el-checkbox__input {
                margin-right: 5px;
              }
              .el-checkbox__label {
                padding: 0;
                width: 134px;
                display: block;
                .permission-text {
                  width: 134px;
                  display: block;
                  font-size: 14px;
                  font-weight: 400;
                  color: #212529;
                }
              }
            }
          }
        }
      }
    }
  }
}
.check-wrap {
  position: relative;
}
.check-header {
  width: 100%;
  height: 40px;
  background: #f8fbfc;
  padding: 0 16px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #ebeff2;
  position: sticky;
  top: 0;
  z-index: 100;
  :deep(.el-checkbox) {
    display: flex;
    flex-direction: row-reverse;
    .el-checkbox__label {
      padding-right: 4px;
      color: #0a1f33;
    }
  }
}
</style>
